import com.alibaba.fastjson.JSONObject;
import wei.yigulu.modbus.domain.ModbusSlaveDataContainer;
import wei.yigulu.modbus.domain.datatype.BooleanModbusDataInCoil;
import wei.yigulu.modbus.domain.datatype.BooleanModbusDataInRegister;
import wei.yigulu.modbus.domain.datatype.ModbusDataTypeEnum;
import wei.yigulu.modbus.domain.datatype.NumericModbusData;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeSet;

public class PointDataContainer {


    private PointDataContainer() {
    }

    /**
     * 获取单例实例
     *
     * @return the instance
     */
    public static final PointDataContainer getInstance() {
        return LazyHolder.INSTANCE;
    }


    private static class LazyHolder {
        private static final PointDataContainer INSTANCE = new PointDataContainer();
    }


    private Map<Integer, BasePointData> pointDataMap = new HashMap<>();


    public void add2PointDataMap(BasePointData pointData) {
        this.pointDataMap.put(pointData.getPoint(), pointData);
        pointData.joinRealTimeData();
    }

    public BasePointData getDataPoint(Integer point) {
       return this.pointDataMap.getOrDefault(point,null);
    }

    public void deleteFromPointDataMap(Integer point) {
        this.pointDataMap.remove(point);
        ProtocolDataContainer.getInstance().removeCalculatorTask(point);
    }

    public JSONObject getAllPoint() {
        JSONObject jsonObject = new JSONObject();
        for (Integer i : new TreeSet<>(this.pointDataMap.keySet())) {
            jsonObject.put(i + "", this.pointDataMap.get(i));
        }
        return jsonObject;
    }

    /**
     * 为modbus的寄存器添加数据
     */
    public void addData2ModbusSlaver(ModbusSlaveDataContainer modbusSlaveDataContainer) {
        BooleanModbusDataInRegister booleanModbusDataInRegister;
        for (Map.Entry<Integer, BasePointData> e : this.pointDataMap.entrySet()) {

            if (ModbusDataTypeEnum.A16 == e.getValue().getDataType()) {
                booleanModbusDataInRegister= new BooleanModbusDataInRegister();
                booleanModbusDataInRegister.setValue(0,ProtocolDataContainer.getInstance().getBoolean(e.getKey()));
                modbusSlaveDataContainer.setRegister(1, e.getKey(),booleanModbusDataInRegister);
            } else {
                modbusSlaveDataContainer.setRegister(1, e.getKey(), ((NumericModbusData) e.getValue().getDataType().getObject()).setValue(ProtocolDataContainer.getInstance().getNumber(e.getKey())));
            }
        }
    }


}
